package com.space.myapollo;

import javax.sql.DataSource;

import org.apache.ibatis.io.VFS;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

@Configuration
@MapperScan(basePackages = {
		"com.space.*.mapper" }, annotationClass = H2.class, sqlSessionTemplateRef = "dsH2SqlSessionTemplate")
public class SqlSessionConfig {

	@Value("${mybatis.typeAliasesPackage}")
	private String typeAliasesPackage;

	// 主数据源 YYGJ数据源
	@Primary
	@Bean("dsH2SqlSessionFactory")
	public SqlSessionFactory dsH2SqlSessionFactory(@Qualifier("h2DataSource") DataSource dataSource) throws Exception {

		MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();// new
																							// SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource);
		sqlSessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/h2/*Mapper.xml"));

		sqlSessionFactory.setConfigLocation(
				new PathMatchingResourcePatternResolver().getResource("classpath:mapper/mybatis-config.xml"));
		sqlSessionFactory.setVfs(SpringBootVFS.class);
		VFS.addImplClass(SpringBootVFS.class);
		// 添加插件
//        sqlSessionFactory.setPlugins(new Interceptor[] { MybatisCommon.getPageHelper() });

		// 扫描别名
		sqlSessionFactory.setTypeAliasesPackage(String.join(",", MybatisCommon.getPackages(typeAliasesPackage)));
		return sqlSessionFactory.getObject();
	}

	@Primary
	@Bean(name = "dslanguoTransactionManager")
	public DataSourceTransactionManager dsyygjTransactionManager(@Qualifier("h2DataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Primary
	@Bean(name = "dsH2SqlSessionTemplate")
	public SqlSessionTemplate dsH2SqlSessionTemplate(
			@Qualifier("dsH2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
